<?php

namespace app\common\model;

use think\Model;
use traits\model\SoftDelete;

class Signup extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'signup';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'pay_status_text',
        'paytime_text',
        'status_text',
        'sign_type_text',
        'signtime_text'
    ];
    

    
    public function getPayStatusList()
    {
        return ['0' => __('Pay_status 0'), '1' => __('Pay_status 1')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['pay_status'] ?? '');
        $list = $this->getPayStatusList();
        return $list[$value] ?? '';
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['paytime'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }


    public function getSigntimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['signtime'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setSigntimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

	public function paySuccess($out_trade_no, $trade_on, $amount){
		$order = $this->where(['out_trade_no' => $out_trade_no])->find();
		if($order){
			// 找个没用的商务码
			$userCode = UserCode::where(['status' => 0])->find();
			$userCode->status = 1;
			$userCode->save();

			$order->pay_status = 1;
			$order->paytime = time();
			$order->trade_no = $trade_on;
			$order->real_amount = $amount;
			$order->user_code = $userCode->user_code;
			return $order->save();
		}else{
			return false;
		}
	}

	protected function getSignTypeList(){
		return ['0' => '免费参观', '1' => '付费参加'];
	}

	protected function getSignTypeTextAttr($value, $data){
        $value = $value ?: ($data['sign_type'] ?? '');
        $list = $this->getSignTypeList();
        return $list[$value] ?? '';
	}
}
